import {messages, deepFullCopy} from 'share/common';
import React from 'react';
import { connect } from 'react-redux';
import {
  Row, Col, Modal, Button, Checkbox, message, Select, Spin, Radio, Switch, Icon, Popover, Input
} from 'antd';
import withDragDropContext from 'components/with-dnd-context';
import 'styles/setting/expense-type/new-expense-type/expense-type-custom.scss';
import 'styles/components/template/drag-widget-page/drag-widget-page.scss';
import expenseTypeService from 'containers/setting/expense-type/expense-type.service';
import DragWidgetItem from 'containers/setting/expense-type/new-expense-type/expense-type-custom/drag-source/drag-widget-item';
import FakeDropLayout from 'containers/setting/expense-type/new-expense-type/expense-type-custom/drop-source/fake-drop-layout';
import PhoneContent from 'containers/setting/expense-type/new-expense-type/expense-type-custom/drop-source/phone-content';
import { LanguageInput } from 'components/index';
import formService from 'containers/setting/form/form.service';
import errorMessage from 'share/errorMessage';
import Condition from 'components/condition';
import IPhoneX from 'components/iphone-x';
import QrCode from 'qrcode.react';
import ExpenseAdditional from 'containers/setting/expense-type/new-expense-type/expense-type-custom/expense-additional/expense-additional';
import MessageKeySetting from 'containers/setting/expense-type/new-expense-type/expense-type-custom/component/message-key-setting';
import CommentSetting from 'containers/setting/expense-type/new-expense-type/expense-type-custom/component/comment-setting';
import ListSelector from 'components/list-selector'
import UnifiedTableConfig from 'components/template/widget/unified-table/UnifiedTableConfig'

const {Option} = Select;
const RadioGroup = Radio.Group;

const {confirm} = Modal;
const { If, Else } = Condition;

class ExpenseTypeCustom extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      customWidget: [],
      nowWidgets: [],
      structureNowWidget: props.structureNowWidget || { messageKey: 'form.description' },
      nowSelectedIndex: -2,
      counter: 0,
      customEnumeration: [],
      loading: true,
      saving: false,
      previewing: false,
      enabledReportKey: false,
      reportValueList: [],
      promptInfo: { enabled: false }, // 【说明文字】相关
      dateLinkageValue: 'none',
      qrcodeValue: '',
      checkVisible: false, // 参与核算的控件是否需要显示
      enabledAccountingKey: false,
      checkList: [], // 参与核算列表
      customEnumerationMessageKey: [], // 值列表的messageKey与值列表项的对应关系
      codeVisible: false,
      originExpenseType: deepFullCopy(props.expenseType),
      ignoreChangeMK: false, // 是否忽略修改的mk
      ignoreRepeatMK: false, // 是否忽略重复的mk
      titleRequired: props.expenseType.titleRequired,
      fisTipsShow: false, // 是否展示附件提示信息
      ffieldTips: '', // 附件提示信息内容
      pisTipsShow: false, // 是否展示事由说明提示信息
      pfieldTips: '', // 事由说明提示信息内容
      oisTipsShow: false, // 是否展示发生日期说明提示信息
      ofieldTips: '' // 发生日期说明提示信息内容
    };
    this.hasError = false;
  }

  componentWillMount() {
    expenseTypeService.getWidgetList().then((res) => {
      this.setState({
        customWidget: res.data.rows,
        loading: false
      });
    });
    this.getSelectOptions();
  }

  componentDidMount() {
    this.getIsShowComponent();
    let {
      counter, promptInfo, occurDateDefaultValue, fisTipsShow, ffieldTips, pisTipsShow, pfieldTips, oisTipsShow, ofieldTips
    } = this.state;
    const { languageList, expenseType } = this.props;
    const nowWidgets = JSON.parse(JSON.stringify(expenseType.fields));
    promptInfo = {
      enabled: expenseType.promptEnabled,
      promptTitle: expenseType.promptTitle,
      promptContent: expenseType.promptContent,
      i18n: expenseType.i18n || {}
    };
    nowWidgets.map((widget) => {
      widget.counterFlag = counter++;
      if (!widget.i18n || JSON.stringify(widget) === '{}') {
        languageList.map((language) => {
          widget.i18n.name.push({
            language: language.code.toLowerCase(),
            value: widget.name
          });
        });
      }
      // 业务用途特殊处理，加个标志
      if (widget.messageKey === 'business.type') {
        widget.isBusinessType = true;
      }
    });
    const nowSelectedIndex = this.props.index;
    let enabledReportKey = false; let
      enabledAccountingKey = false;
    if (nowWidgets.length > 0 && nowSelectedIndex === -1) {
      // nowSelectedIndex = 0;
      enabledReportKey = Boolean(nowWidgets[0].reportKey);
      enabledAccountingKey = Boolean(nowWidgets[0].accountingKey);
    } else if (nowSelectedIndex > -1) {
      enabledReportKey = Boolean(nowWidgets[nowSelectedIndex].reportKey);
      enabledAccountingKey = Boolean(nowWidgets[nowSelectedIndex].accountingKey);
    }
    occurDateDefaultValue = expenseType.occurDateDefaultValue;
    fisTipsShow = expenseType.fisTipsShow;
    ffieldTips = expenseType.ffieldTips;
    pisTipsShow = expenseType.pisTipsShow;
    pfieldTips = expenseType.pfieldTips;
    oisTipsShow = expenseType.oisTipsShow;
    ofieldTips = expenseType.ofieldTips;
    const dateLinkageValue = expenseType.dateLinkageValue || 'none';
    this.setState({
      nowWidgets,
      counter,
      nowSelectedIndex,
      enabledReportKey,
      promptInfo,
      occurDateDefaultValue,
      dateLinkageValue,
      enabledAccountingKey,
      fisTipsShow,
      ffieldTips,
      pisTipsShow,
      pfieldTips,
      oisTipsShow,
      ofieldTips
    });
  }

  // 判断某个组件是否展示
  getIsShowComponent = () => {
    // 参与核算 是否显示
    expenseTypeService.isShowCheckBox().then((res) => {
      this.setState({ checkVisible: res.data });
    });
  };

  // 获取下拉选项列表
  getSelectOptions = () => {
    const { company } = this.props;
    // 获取值列表选项
    formService.getCustomEnumeration(0, 100, true).then((res) => {
      this.setState({ customEnumeration: res.data });
    });
    // 获取报表选项
    formService.getExpenseReportScope(4003).then((res) => {
      this.setState({ reportValueList: res.data || [] });
    });
    // 获取核算列表
    expenseTypeService.getCheckList(company.setOfBooksId).then((res) => {
      this.setState({ checkList: res.data || [] });
    });
    // 获取值列表messageKey与值列表项的对应关系，是为了在有对应关系时禁止选择值列表项
    expenseTypeService.getMessageKeyList('CUSTOM_ENUMERATION').then((res) => {
      this.setState({ customEnumerationMessageKey: res.data.rows || [] });
    });
  };

  /**
   * 从列表中把widget拖拽入phone-content时的事件
   * @param widget 拖入的widget
   * @param index 放下的顺序
   */
  handleDrop = (widget, index) => {
    if (!this.props.tenantMode) {
      return;
    }
    let { nowWidgets, counter } = this.state;
    const { languageList, expenseType } = this.props;
    const rules = [{
      type: ['DATE', 'MONTH', 'DATETIME'],
      max: 10
    }, {
      type: ['TEXT', 'GPS', 'CUSTOM_ENUMERATION'],
      max: 100 // 临时修改，等相关费用类型配置完成后改回9个
    }, {
      type: ['START_DATE_AND_END_DATE'],
      max: 1
    }, {
      type: ['LONG', 'POSITIVE_INTEGER'],
      max: 5
    }, {
      type: ['DOUBLE'],
      max: 5
    }, {
      type: ['BOOLEAN'],
      max: 3
    }, {
      type: ['LOCATION'],
      max: 2
    }, {
      type: ['PARTICIPANT'],
      max: 1
    }, {
      type: ['PARTICIPANTS'],
      max: 1
    }, {
      type: ['COMPANY_PAID'],
      max: 1
    }, {
      type: ['ASSOCIATE_APPLICATION'],
      max: 10
    }];
    let targetRule = {};
    rules.map((rule) => {
      if (rule.type.indexOf(widget.fieldType) > -1) targetRule = rule;
      // 业务用途是特殊的值列表，最多添加一个
      if (widget.fieldType === 'CUSTOM_ENUMERATION' && widget.messageKey === 'business.type') {
        targetRule = {
          type: ['CUSTOM_ENUMERATION'],
          max: 1
        };
      }
    });
    let limit = 0;
    nowWidgets.map((nowWidget) => {
      // 业务用途特殊处理
      if (widget.messageKey === 'business.type') {
        if (nowWidget.messageKey === 'business.type') {
          limit++;
        }
      } else if (~targetRule.type.indexOf(nowWidget.fieldType)) {
        if (~['TEXT', 'GPS', 'CUSTOM_ENUMERATION'].indexOf(widget.fieldType)) {
          nowWidget.messageKey !== 'business.type' && limit++;
        } else {
          limit++;
        }
      }
    });
    if (limit >= targetRule.max) {
      message.error(messages('setting.key1453', {arg1: targetRule.max}/* 该类组件最多只能存在{arg1}个 */));
      return;
    }
    const tempWidget = JSON.parse(JSON.stringify(widget));
    // 因为ListSort根据key值排序，key值不能改变和重复，所以此处给每一个拖拽进入的组件一个counter计数为counterFlag
    tempWidget.counterFlag = counter++;
    const i18nName = deepFullCopy(tempWidget.i18n);
    tempWidget.i18n = {
      name: []
    };
    languageList.map((language) => {
      i18nName.map((i18nItem) => {
        if (language.code.toLowerCase() === i18nItem.language) {
          tempWidget.i18n.name.push({
            language: i18nItem.language,
            value: i18nItem.name
          });
        }
      });
    });
    tempWidget.editable = true;
    // 第三方费用（里程补贴的readonly是true，但是他是可以编辑的）默认不可编辑
    expenseType && expenseType.readonly && expenseType.messageKey !== 'private.car.for.public' && (tempWidget.editable = false);
    tempWidget.showOnList = true;
    // 业务用途特殊处理，加个标志
    if (tempWidget.messageKey === 'business.type') {
      tempWidget.isBusinessType = true;
    }
    nowWidgets.splice(index, 0, tempWidget);
    this.setState({ nowWidgets, counter, nowSelectedIndex: index });
    this.handleSelectWidget(index, nowWidgets);
  };

  /**
   * 选择某一组件时的回调
   * @param nowSelectedIndex  列表中的第几个
   * @param widget  对应widget对象
   */
  handleSelectWidget = (nowSelectedIndex, widget) => {
    this.setState({
      nowSelectedIndex,
      enabledReportKey: Boolean(widget.reportKey),
      enabledAccountingKey: Boolean(widget.accountingKey),
      structureNowWidget: ~[-1, -2, -3, -4].indexOf(nowSelectedIndex) ? widget : null
    });
  };

  /**
   * phone-content内部排序后的事件
   * @param result 返回的ReactDom，key值为拖拽进入时定义的counterFlag
   */
  handleSort = (result) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    // 记录当前选择的counterFlag
    const nowSelectWidgetCounter = nowWidgets[nowSelectedIndex].counterFlag;
    let targetIndex = -1;
    const tempWidget = [];
    // 根据排序后的key值排序
    result.map((item) => {
      nowWidgets.map((widget) => {
        (`${widget.counterFlag}`) === item.key && tempWidget.push(widget);
      });
    });
    // 寻找之前选择的index
    tempWidget.map((item, index) => {
      if (item.counterFlag === nowSelectWidgetCounter) targetIndex = index;
    });
    this.setState({ nowWidgets: tempWidget, nowSelectedIndex: targetIndex });
  };

  /**
   * phone-content内部删除后的事件
   * @param index 待删除的索引
   */
  handleDelete = (index) => {
    if (!this.props.tenantMode) {
      return;
    }
    const { expenseTypeId } = this.props;
    let { nowWidgets, nowSelectedIndex } = this.state;
    confirm({
      title: messages('setting.key564'/* 你确定要删除这个组件吗? */),
      content: messages('setting.key565'/* 配置项将不会保存 */),
      okType: 'danger',
      okText: messages('common.delete'),
      cancelText: messages('common.cancel'),
      onOk: () => {
        const {mappedColumnId} = nowWidgets[nowSelectedIndex];
        expenseTypeService.checkFieldCanDelete(expenseTypeId, mappedColumnId).then((res) => {
          if (res.data.success) {
            nowWidgets.splice(index, 1);
            nowSelectedIndex = -1;
            if (nowWidgets.length > 0) {
              nowSelectedIndex = 0;
            }
            this.setState({ nowWidgets, nowSelectedIndex });
          } else {
            message.error(res.data.message);
          }
        }).catch((e) => {
          message.error(e.response.data.message);
        });
      }
    });
  };

  getWidgetType = () => {
    const { nowWidgets, nowSelectedIndex, customWidget } = this.state;
    let widgetType = nowWidgets[nowSelectedIndex].fieldType;
    let result = <Spin />;
    if (nowWidgets[nowSelectedIndex].customEnumerationOID) widgetType = 'CUSTOM_ENUMERATION';
    if (nowWidgets[nowSelectedIndex].messageKey === 'dateCombined') widgetType = 'START_DATE_AND_END_DATE';
    customWidget.map((item) => {
      if (nowWidgets[nowSelectedIndex].messageKey === 'business.type') { // 业务用途
        if (item.messageKey === 'business.type') {
          result = item.name;
        }
      } else if (widgetType === item.fieldType && item.messageKey !== 'business.type') {
        result = item.name;
      }
    });
    return result;
  };

  handleChangeWightI18n = (value, i18n) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    nowWidgets[nowSelectedIndex].name = value;
    nowWidgets[nowSelectedIndex].i18n = {
      name: i18n
    };
    this.setState({ nowWidgets });
  };

  /**
   * 控件的Checkbox组件或Radio组件修改时
   * @param e
   * @param key: 需要修改的字段
   * @param isRadio: 是否为Radio组件，默认false
   */
  handleChangeCheckBox = (e, key, isRadio = false) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    if (['addToSummary', 'participantsRange'].includes(key)) {
      const config = nowWidgets[nowSelectedIndex].config || {};
      config[key] = isRadio ? e.target.value : e.target.checked;
      nowWidgets[nowSelectedIndex].config = config;
    } else {
      nowWidgets[nowSelectedIndex][key] = e.target.checked;
    }
    this.setState({ nowWidgets });
  };

  handleChangeStructureCheckBox = (e, type) => {
    const { expenseType } = this.props;
    if (type === 'timeSupported') {
      expenseType.timeSupported = e.target.checked;
    }
    if (type === 'autoTimeSupported') {
      this.setState({ occurDateDefaultValue: e.target.value });
    }
    if (type === 'dateLinkageValue') {
      this.setState({ dateLinkageValue: e.target.value });
    }
  };

  /**
   * 处理数据
   * @param callback
   * @returns {*}
   */
  handleExpenseData = (callback) => {
    const {
      nowWidgets, nowSelectedIndex, enabledAccountingKey, ignoreChangeMK, ignoreRepeatMK, originExpenseType
    } = this.state;
    this.hasError = false;
    if (enabledAccountingKey && !nowWidgets[nowSelectedIndex].accountingKey) {
      this.hasError = true;
      message.error(messages('setting.key2037')/* 请选择参与核算项 */);
    }
    nowWidgets.map((widget, index) => {
      widget.sequence = index;
      // 控件的messageKey为空时，值要传null
      widget.messageKey = widget.messageKey ? widget.messageKey : null;
      if (!widget.name) {
        this.hasError = true;
        message.error(messages('setting.key1454', {arg1: index + 1}/* 第{arg1}个自定义组件的标题未填 */));
      }
      if (widget.fieldType === 'CUSTOM_ENUMERATION' && widget.messageKey !== 'business.type' && !widget.customEnumerationOID) {
        this.hasError = true;
        message.error(messages('setting.key1455', {arg1: index + 1}/* 第{arg1}个自定义组件的值列表未选择 */));
      }
      if (widget.fieldType === 'COMPANY_PAID') {
        widget.defaultValueKey = widget.defaultValueKey || '1001';
      }
      if (widget.fieldType === 'BOOLEAN') {
        widget.defaultValueKey = false;
      }
      if (widget.fieldType === 'PARTICIPANTS') {
        const config = widget.config || {};
        !config.participantsRange && (config.participantsRange = 3);
        widget.config = config;
      }
      if (widget.messageKey) {
        const reg = widget.messageKey.length === 1 ? /[a-zA-Z]/ : /^[a-zA-Z][\.a-zA-Z]*[a-zA-Z]$/;
        let widgetIsNew = true; // 该widget是否为新增字段
        originExpenseType.fields && originExpenseType.fields.map((item) => {
          item.fieldOID === widget.fieldOID && (widgetIsNew = false);
        });
        // widget为新增字段 或 编辑并messageKey改变的字段时，需要校验格式是否正确
        // 因为老数据的messageKey会存在"-","_"等特殊字符，新保存的messageKey只能由字母和小数点组成
        if (widgetIsNew || (!widgetIsNew && this.checkMessageKeyIsChange(widget))) {
          if (!reg.test(widget.messageKey)) {
            this.hasError = true;
            message.error(messages('setting.key2102')/* 业务编码首尾必须为字母 */);
          }
        }
      }
      if (!this.hasError && !ignoreChangeMK && this.checkMessageKeyIsChange(widget)) {
        this.hasError = true;
        Modal.confirm({
          title: messages('setting.key2104')/* 修改“业务编码”，可能会影响应用原始业务编码的相关功能 */,
          onOk: () => this.setState({ ignoreChangeMK: true }, callback)
        });
      }
    });
    if (!this.hasError && !ignoreRepeatMK && this.checkMessageKeyIsRepeat()) {
      this.hasError = true;
      Modal.confirm({
        title: messages('setting.key2137')/* 该费用类型控件存在重复的“业务编码”，可能影响该“业务编码”的应用，确定保存？ */,
        onOk: () => this.setState({ ignoreRepeatMK: true }, callback),
        onCancel: () => this.setState({ ignoreChangeMK: false })
      });
    }
    return nowWidgets;
  };

  // 检查messageKey是否有改变
  checkMessageKeyIsChange = (widget) => {
    const { originExpenseType } = this.state;
    let isChange = false;
    if (originExpenseType.fields && originExpenseType.fields.length && widget) {
      originExpenseType.fields.map((fieldItem) => {
        if (fieldItem.fieldOID === widget.fieldOID && fieldItem.messageKey !== widget.messageKey) {
          isChange = true;
        }
      });
    }
    return isChange;
  };

  // 检查messageKey是否有重复
  checkMessageKeyIsRepeat = () => {
    const { nowWidgets } = this.state;
    let hasRepeat = false;
    nowWidgets.map((widget, index) => {
      nowWidgets.map((item, itemIndex) => {
        if (itemIndex !== index && item.messageKey && item.messageKey === widget.messageKey) {
          hasRepeat = true;
        }
      });
    });
    return hasRepeat;
  };

  handleSave = () => {
    const { expenseType } = this.props;
    const {
      nowSelectedIndex,
      promptInfo,
      structureNowWidget,
      occurDateDefaultValue,
      dateLinkageValue,
      titleRequired,
      fisTipsShow,
      ffieldTips,
      pisTipsShow,
      pfieldTips,
      oisTipsShow,
      ofieldTips
    } = this.state;
    const nowWidgets = this.handleExpenseData(this.handleSave);
    if (!this.hasError) {
      this.setState({ saving: true });
      expenseTypeService.saveExpenseTypeFields(expenseType.id, {
        fields: nowWidgets,
        timeSupported: expenseType.timeSupported,
        promptEnabled: promptInfo.enabled,
        promptTitle: promptInfo.promptTitle,
        promptContent: promptInfo.promptContent,
        titlePlaceholder: promptInfo.titlePlaceholder,
        i18n: promptInfo.i18n,
        occurDateDefaultValue,
        dateLinkageValue,
        titleRequired,
        fisTipsShow,
        ffieldTips,
        pisTipsShow,
        pfieldTips,
        oisTipsShow,
        ofieldTips
      }).then((res) => {
        this.setState({ saving: false });
        message.success(messages('common.operate.success'));
        this.props.saveIndex(nowSelectedIndex, structureNowWidget);
        this.props.onSave();
      }).catch((e) => {
        this.setState({ saving: false });
        errorMessage(e.response);
      });
    }
  };

  handlePreview = () => {
    const { expenseType } = this.props;
    const {
      promptInfo, occurDateDefaultValue, dateLinkageValue, titleRequired
    } = this.state;
    const nowWidgets = this.handleExpenseData(this.handlePreview);
    if (!this.hasError) {
      this.setState({ previewing: true, codeVisible: true });
      expenseTypeService.saveExpenseTypeFields(expenseType.id, {
        fields: nowWidgets,
        timeSupported: expenseType.timeSupported,
        promptEnabled: promptInfo.enabled,
        promptTitle: promptInfo.promptTitle,
        promptContent: promptInfo.promptContent,
        titlePlaceholder: promptInfo.titlePlaceholder,
        i18n: promptInfo.i18n,
        occurDateDefaultValue,
        dateLinkageValue,
        titleRequired
      }).then(() => {
        // 预览并保存后页面不会刷新，所以props.expenseType不会更新，state.originExpenseType也不会更新
        // 所以为了校验messageKey是否发生变化，手动更新state.originExpenseType的fields字段
        const { originExpenseType } = this.state;
        originExpenseType.fields.map((item) => {
          nowWidgets.map((widgetItem) => {
            widgetItem.fieldOID === item.fieldOID && (item.messageKey = widgetItem.messageKey);
          });
        });
        this.setState({
          previewing: false,
          ignoreChangeMK: false,
          ignoreRepeatMK: false,
          originExpenseType,
          qrcodeValue: `helios://preview?appCode=EXPENSE_LIST&id=${expenseType.id}&expenseTypeOID=${expenseType.expenseTypeOID}`
        });
        message.success(messages('common.save.success', {name: ''}));
      }).catch((e) => {
        this.setState({ previewing: false, ignoreChangeMK: false, ignoreRepeatMK: false });
        errorMessage(e.response);
      });
    }
  };

  handleChangeCustomEnumeration = (value) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    nowWidgets[nowSelectedIndex].customEnumerationOID = value;
    this.setState({ nowWidgets });
  };

  // 修改下拉框选择值
  handleChangeSelect = (value, key) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    nowWidgets[nowSelectedIndex][key] = value;
    this.setState({ nowWidgets });
  };

  // 修改有联动关系的复选框的值（报表、核算）
  handleChangeLinkageCheckbox = (e, key, enabledKey) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    if (!e.target.checked) {
      nowWidgets[nowSelectedIndex][key] = null;
    }
    this.setState({
      [enabledKey]: e.target.checked,
      nowWidgets
    });
  };

  // 费用开始结束日期控件计算逻辑配置
  handleChangeTotalDateChange = (e) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    const config = nowWidgets[nowSelectedIndex].config || {};
    config.daysComputeMode = e.target.value;
    nowWidgets[nowSelectedIndex].config = config;
    this.setState({ nowWidgets });
  };

  // 更新控件的config配置
  handleNowSelectedWidgetConfigChange = (partialConfig = {}) => {
    this.setState(({ nowWidgets, nowSelectedIndex}) => {
      return {
        nowWidgets: nowWidgets.map((item, index) => {
          if (index === nowSelectedIndex) {
            return {
              ...item,
              ...partialConfig
            };
          }
          return item;
        })
      };
    }, () => {
      // console.log('nowWidgets', this.state.nowWidgets);
    });
  }

  // 修改公司已付控件的默认值
  handleChangeCompanyPaidValue = (e) => {
    const { nowWidgets, nowSelectedIndex } = this.state;
    nowWidgets[nowSelectedIndex].defaultValueKey = e.target.value;
    this.setState({ nowWidgets });
  };

  // 修改多语言的值
  handleLanguageInput = (name, i18n, attr) => {
    const { promptInfo } = this.state;
    promptInfo[attr] = name;
    promptInfo.i18n = promptInfo.i18n || {};
    promptInfo.i18n[attr] = i18n;
    this.setState({ promptInfo });
  };

  // 修改说明文字是否显示
  handleFormDescChange = (enabled) => {
    const { promptInfo } = this.state;
    promptInfo.enabled = enabled;
    this.setState({ promptInfo });
  };

  handleSelected = (applicationScopMap) => { //  关联申请单选中值
    const { nowWidgets, nowSelectedIndex } = this.state;
    nowWidgets[nowSelectedIndex].config = { applicationScopMap };
  };

   // 开关：是否显示信息提示
   handleFieldTipsShowChange = (show) => {
     const nowWidgets = this.state.nowWidgets.slice();
     nowWidgets[this.state.nowSelectedIndex].isTipsShow = show;
     this.setState({
       nowWidgets
     });
   }
  // 开关：是否显示联动按钮
   handleFieldBtnShowChange = (show) => {
    const nowWidgets = this.state.nowWidgets.slice();
    nowWidgets[this.state.nowSelectedIndex].isHidden = show;
    this.setState({
      nowWidgets
    });
   }

  // 文本：是否显示信息提示
  handleFieldTipsChange = (e) => {
    const nowWidgets = this.state.nowWidgets.slice();
    nowWidgets[this.state.nowSelectedIndex].fieldTips = e.target.value;
    this.setState({
      nowWidgets
    });
  }

  handleFieldBtnChange = (e) => {
    const nowWidgets = this.state.nowWidgets.slice();
    nowWidgets[this.state.nowSelectedIndex].switchText = e.target.value;
    this.setState({
      nowWidgets
    });
  }

  // 保存并预览表单二维码
  renderPreviewQCode = () => {
    const { previewing, qrcodeValue } = this.state;
    return (
      <Spin spinning={previewing}>
        {qrcodeValue
          ? (
            <div style={qrcodeValue === 'timeout' ? {position: 'relative', opacity: 0.5} : {}}>
              <QrCode
              value={qrcodeValue}
              renderAs="svg"
              fgColor="#000000"
              size={160}
            />
              {qrcodeValue === 'timeout' && <div className="qrcode-timeout">{messages('setting.key2105')/* 二维码已过期 */}</div>}
            </div>
          )
          : messages('setting.key2106')/* 预览失败 */}
        <div style={{textAlign: 'center'}}>
          {(!qrcodeValue || qrcodeValue === 'timeout')
            ? messages('setting.key1989')
            :/* 请重新点击预览 */ messages('setting.key1990')/* 请使用汇联易扫码预览 */}
        </div>
      </Spin>
    );
  };

  // 选择值列表项是否可编辑
  customEnumerationDisabled = (nowWidget) => {
    const { customEnumerationMessageKey, customEnumeration } = this.state;
    let disabled = false;
    let valueListType = null;
    // 根据当前字段的customEnumerationOID获取对应值列表项的systemCustomEnumerationType
    if (nowWidget.customEnumerationOID) {
      customEnumeration.forEach((item) => {
        if (item.customEnumerationOID === nowWidget.customEnumerationOID) {
          valueListType = item.systemCustomEnumerationType;
        }
      });
    }
    if (valueListType) {
      customEnumerationMessageKey.forEach((item) => {
        // 当前字段的messageKey和值列表项的对应关系一致时，不可编辑
        if (item.businessKey === nowWidget.messageKey && String(item.valueListType) === String(valueListType)) {
          disabled = true;
        }
      });
    }
    return disabled;
  };

  changeSwitchStatus = (checked) => {
    if (!checked) {
      // this.handleDelete(this.state.nowSelectedIndex)
      if (!this.props.tenantMode) {
        return;
      } else {
        console.log(1)
        let { nowWidgets, nowSelectedIndex } = this.state;
        nowWidgets.splice(nowSelectedIndex, 1);
        nowSelectedIndex = -1;
        if (nowWidgets.length > 0) {
          nowSelectedIndex = 0;
        }
        this.setState({ nowWidgets, nowSelectedIndex });
      }
    }
  }

  render() {
    const {
      customWidget, nowWidgets, nowSelectedIndex, customEnumeration, loading, saving, enabledReportKey,
      reportValueList, structureNowWidget, promptInfo, occurDateDefaultValue, dateLinkageValue, checkList,
      enabledAccountingKey, checkVisible, codeVisible, originExpenseType, titleRequired, fisTipsShow, ffieldTips, pisTipsShow, pfieldTips, oisTipsShow, ofieldTips
    } = this.state;
    const { tenantMode, expenseType } = this.props;
    const nowWidget = nowSelectedIndex > -1 ? nowWidgets[nowSelectedIndex] : null;
    console.log('nowWidget', nowWidget)
    return (
      <div className="drag-widget-page expense-type-custom">
        <FakeDropLayout />
        <Row gutter={40}>
          <Col span={8}>
            {loading ? <Spin /> : (
              <div className="widget-area">
                <div className="widget-list">
                  <div className="widget-category">{messages('setting.key566'/* 系统控件 */)}</div>
                  <div className="widget-list">
                    {customWidget.filter((widget) => widget.type === 'SYSTEM').map((widget) => (
                      <DragWidgetItem widget={widget}
                                                                                                           key={widget.id} />
                    ))}
                  </div>
                  <div className="widget-category">{messages('setting.key567'/* 自定义控件 */)}</div>
                  <div className="widget-list">
                    {customWidget.filter((widget) => widget.type === 'CUSTOM').map((widget) => (
                      <DragWidgetItem widget={widget}
                                                                                                           key={widget.id} />
                    ))}
                  </div>
                </div>
              </div>
            )}
          </Col>
          <Col span={8}>
            <IPhoneX type="iPhoneX" title={expenseType.name}>
              <PhoneContent
                widgetList={nowWidgets}
                onSort={this.handleSort}
                nowSelectedIndex={nowSelectedIndex}
                onSelect={this.handleSelectWidget}
                onDrop={this.handleDrop}
                onDelete={this.handleDelete}
                promptInfo={promptInfo}
                disabled={!tenantMode}
                expenseType={originExpenseType}
                changeSwitchStatus={this.changeSwitchStatus}
              />
            </IPhoneX>
          </Col>
          <Col span={8} className="widget-setting">
            {nowWidget ? (
              <div>
                {messages('setting.key505'/* 类型 */)}
                :
                {this.getWidgetType()}
                <div className="widget-setting-title">{messages('setting.key568'/* 标题 */)}</div>
                <div className="field-tips">
                  <div className="widget-setting-title">
                    提示信息: &nbsp;
                    <Switch
                    checked={nowWidget.isTipsShow || false}
                    checkedChildren={<Icon type="check" />}
                    unCheckedChildren={<Icon type="cross" />}
                    onChange={(e) => this.handleFieldTipsShowChange(e)}
                   />
                  </div>
                  {nowWidget.isTipsShow && (
                    <div>
                      <Input placeholder="请输入提示信息" onChange={(e) => this.handleFieldTipsChange(e)} value={nowWidget.fieldTips || ''} />
                    </div>
                  )}
                </div>
                {nowWidget.messageKey === 'associate.application' || nowWidget.messageKey === 'public.assembly' ?
                  <div className="field-tips" style={{ marginBottom: 10 }}>
                    <div className="widget-setting-title">
                      是否显示联动按钮: &nbsp;
                      <Switch
                        checked={nowWidget.isHidden || false}
                        checkedChildren={<Icon type="check" />}
                        unCheckedChildren={<Icon type="cross" />}
                        onChange={e => this.handleFieldBtnShowChange(e)}
                      />
                    </div>
                    {nowWidget.isHidden && (
                      <div>
                        <Input placeholder="请输入提示信息" onChange={(e) => this.handleFieldBtnChange(e)} value={nowWidget.switchText || ''} />
                      </div>
                    )}
                  </div> : ''
                }
                <LanguageInput
                  isEdit
                  name={nowWidget.name}
                  i18nName={JSON.parse(JSON.stringify(nowWidget.i18n.name))}
                  nameChange={this.handleChangeWightI18n}
                  disabled={!tenantMode}
                  inpRule={[{
                    length: 30,
                    language: 'zh_cn'
                  }, {
                    length: 100,
                    language: 'en'
                  }]}
                />
                <MessageKeySetting
                  widget={nowWidget}
                  customEnumeration={customEnumeration || []}
                  onChange={(value) => {
                    const { nowWidgets } = this.state;
                    nowWidgets[nowSelectedIndex] = value;
                    this.setState({ nowWidgets });
                  }}
                />
                {/* public.assembly */}
                {nowWidget.fieldType === 'TEXT' && nowWidget.messageKey === 'public.assembly' && (
                  <UnifiedTableConfig pkId={expenseType.id} defaultValue={nowWidget} onChange={this.handleNowSelectedWidgetConfigChange}></UnifiedTableConfig>
                )}

                {/* 需求4140：费用开始结束日期控件计算逻辑配置 */}
                {(nowWidget.fieldType === 'START_DATE_AND_END_DATE'
                  || (nowWidget.fieldType === 'TEXT' && nowWidget.messageKey === 'dateCombined')) && (
                  <div>
                    <div className="widget-setting-title">{messages('setting.key1659')/* 总天数计算逻辑 */}</div>
                    <RadioGroup value={nowWidget.config ? Number(nowWidget.config.daysComputeMode || 1) : 1}
                                disabled={!tenantMode}
                                onChange={this.handleChangeTotalDateChange}>
                      <Radio value={1}>{messages('setting.key1660')/* 结束日期 - 开始日期 */}</Radio>
                      <Radio value={2}>
                        {messages('setting.key1660')/* 结束日期 - 开始日期 */}
                        {' '}
                        + 1
                      </Radio>
                    </RadioGroup>
                  </div>
                )}
                {(nowWidget.fieldType === 'CUSTOM_ENUMERATION'
                  || (nowWidget.fieldType === 'TEXT' && nowWidget.customEnumerationOID)) && (
                  <div>
                    <div className="widget-setting-title">{messages('setting.key569'/* 自定义值列表 */)}</div>
                    <Condition>
                      <If value={nowWidget.messageKey === 'business.type'}>
                        <Input value={messages('setting.key2038')/* 业务用途 */} disabled />
                      </If>
                      <Else>
                        {loading ? <Spin /> : (
                          <Select
                            showSearch
                            style={{ width: '100%' }}
                            value={nowWidget.customEnumerationOID}
                            onChange={this.handleChangeCustomEnumeration}
                            filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                            disabled={!tenantMode || this.customEnumerationDisabled(nowWidget)}
                          >
                            {customEnumeration.map((enumeration) => (
                              <Option value={enumeration.customEnumerationOID}
                                      key={enumeration.customEnumerationOID}>
                                {enumeration.name}
                              </Option>
                            ))}
                          </Select>
                        )}
                      </Else>
                    </Condition>
                  </div>
                )}
                <CommentSetting
                  fieldType={nowWidget.fieldType}
                  expenseType={expenseType}
                  nowWidget={nowWidget}
                  nowSelectedIndex={nowSelectedIndex}
                  onChange={(originExpenseType) => this.setState({ originExpenseType })}
                />
                <If value={nowWidget.fieldType === 'COMPANY_PAID'}>
                  <div className="widget-setting-title">{messages('setting.key1719')/* 默认状态 */}</div>
                  <Condition>
                    {/* 里程补贴的readonly是true，但是他是可以编辑的 */}
                    <If value={expenseType.readonly && expenseType.messageKey !== 'private.car.for.public'}>
                      <div style={{color: '#bbb'}}>{messages('setting.key1720')/* 由供应商推送 */}</div>
                    </If>
                    <Else>
                      <RadioGroup value={nowWidget.defaultValueKey || '1001'}
                                  disabled={!tenantMode}
                                  onChange={this.handleChangeCompanyPaidValue}>
                        <Radio value="1001">{messages('setting.key1721')/* 关闭 */}</Radio>
                        <Radio value="1002">{messages('setting.key1722')/* 开启 */}</Radio>
                      </RadioGroup>
                    </Else>
                  </Condition>
                </If>
                <If value={!~['COMPANY_PAID'].indexOf(nowWidget.fieldType)}>
                  <div className="widget-setting-title">
                    <Checkbox onChange={(e) => this.handleChangeCheckBox(e, 'required')}
                              checked={nowWidget.required}
                              disabled={!tenantMode}>
                      {messages('setting.key570'/* 是否必填 */)}
                    </Checkbox>
                  </div>
                </If>
                <div className="widget-setting-title">
                  <Checkbox onChange={(e) => this.handleChangeCheckBox(e, 'showOnList')}
                            checked={nowWidget.showOnList}
                            disabled={!tenantMode}>
                    {messages('setting.key571'/* 是否显示 */)}
                  </Checkbox>
                </div>
                <If value={!~['COMPANY_PAID'].indexOf(nowWidget.fieldType)}>
                  <div className="widget-setting-title">
                    <Checkbox onChange={(e) => this.handleChangeCheckBox(e, 'printHide')}
                              checked={nowWidget.printHide}
                              disabled={!tenantMode}>
                      {messages('setting.key572'/* 打印是否隐藏 */)}
                    </Checkbox>
                  </div>
                </If>
                <div className="widget-setting-title">
                  <Checkbox onChange={(e) => this.handleChangeCheckBox(e, 'editable')}
                              checked={nowWidget.editable}
                              disabled={
                                !tenantMode
                                || (nowWidget.fieldType === 'COMPANY_PAID' && (
                                  expenseType.readonly && expenseType.messageKey !== 'private.car.for.public'
                                ))
                              }>
                    {messages('setting.key573'/* 是否可编辑 */)}
                  </Checkbox>
                </div>
                <If value={!~['COMPANY_PAID'].indexOf(nowWidget.fieldType)}>
                  <div className="widget-setting-title">
                    <Checkbox onChange={(e) => this.handleChangeLinkageCheckbox(e, 'reportKey', 'enabledReportKey')}
                              checked={enabledReportKey}
                              disabled={!tenantMode}>
                      {messages('setting.key574'/* 是否加入报表 */)}
                      <span className="widget-setting-checkbox-info">{messages('setting.key575'/* 可以在报表下载页面，样表中设置别名 */)}</span>
                    </Checkbox>
                    {!loading && enabledReportKey && (
                      <Select showSearch
                              value={nowWidget.reportKey || undefined}
                              onChange={(e) => this.handleChangeSelect(e, 'reportKey')}
                              filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                              style={{ marginTop: 5, width: '100%' }}
                              placeholder={messages('common.please.select')}
                              disabled={!tenantMode}>
                        {reportValueList.filter((enumeration) => enumeration.enabled).map((enumeration) => (
                          <Option value={enumeration.value}
                                  key={enumeration.value}>
                            {enumeration.messageKey}
                          </Option>
                        ))}
                      </Select>
                    )}
                  </div>
                </If>
                <If value={!~['COMPANY_PAID'].indexOf(nowWidget.fieldType)}>
                  <div className="widget-setting-title">
                    <Checkbox onChange={(e) => this.handleChangeCheckBox(e, 'addToSummary')}
                              checked={(nowWidget.config || {}).addToSummary}
                              disabled={!tenantMode}>
                      {' '}
                      {messages('setting.key1677')/* 摘要中显示该字段 */}
                      <span className="widget-setting-checkbox-info">
                        {' '}
                        {messages('setting.key1678')/* 显示顺序同左侧费用类型中显示的顺序 */}
                      </span>
                    </Checkbox>
                  </div>
                </If>
                <If value={nowWidget.fieldType === 'ASSOCIATE_APPLICATION'}>
                  <ExpenseAdditional
                    title={messages('setting.key2094')/* 请选择可关联的申请单 */}
                    disabled={!tenantMode}
                    checkable={false}
                    checkStrictly
                    onChange={this.handleSelected}
                    nowWidget={nowWidget}
                  />
                </If>
                {checkVisible && (
                  <div>
                    <div className="widget-setting-title">
                      <Checkbox
                        disabled={!tenantMode}
                        onChange={(e) => this.handleChangeLinkageCheckbox(e, 'accountingKey', 'enabledAccountingKey')}
                        checked={enabledAccountingKey}
                      >
                        {messages('setting.key2039')/* 参与核算 */}
                      </Checkbox>
                    </div>
                    <If value={enabledAccountingKey}>
                      <Select
                        disabled={!tenantMode}
                        getPopupContainer={(triggerNode) => triggerNode.parentNode}
                        onChange={(e) => this.handleChangeSelect(e, 'accountingKey')}
                        value={checkList.length ? nowWidget.accountingKey || undefined : undefined}
                        placeholder={`${messages('common.please.select')/* 请选择 */}（${messages('setting.key1798')/* 必填 */}）`}
                      >
                        {checkList.map((item) => (
                          <Option key={item.id}>{item.segmentName}</Option>
                        ))}
                      </Select>
                    </If>
                  </div>
                )}
                <If value={~['PARTICIPANTS'].indexOf(nowWidget.fieldType)}>
                  <div className="form-title">{messages('setting.key2174')/* 控件选人范围设置 */}</div>
                  <div className="widget-setting-title">
                    <RadioGroup
                      disabled={!tenantMode}
                      onChange={(e) => this.handleChangeCheckBox(e, 'participantsRange', true)}
                      value={(nowWidget.config || {}).participantsRange || 3}
                    >
                      <Radio value={1}>{messages('setting.key2175')/* 费用归属人所属公司 */}</Radio>
                      <br />
                      <Radio value={2}>{messages('setting.key2176')/* 费用归属人所属帐套 */}</Radio>
                      <br />
                      <Radio value={3}>{messages('setting.key2177')/* 费用归属人所属租户 */}</Radio>
                      <br />
                      <Radio value={4}>
                        {messages('setting.key2212')/* 同报销单的参与人范围 */}
                        <span className="font-disabled">
                          （
                          {messages('setting.key2213')/* 在账本中默认所属租户 */}
                          ）
                        </span>
                      </Radio>
                      <br />
                      <Radio value={5}>
                        {messages('setting.key2214')/* 同报销单的成本中心 */}
                        <span className="font-disabled">
                          （
                          {messages('setting.key2213')/* 在账本中默认所属租户 */}
                          ）
                        </span>
                      </Radio>
                    </RadioGroup>
                  </div>
                </If>
              </div>
            ) : (
              structureNowWidget ? (
                <div>
                  <If value={structureNowWidget.fieldType === 'createdTime'}>
                    {messages('setting.key505'/* 类型 */)}
                    :
                    {structureNowWidget.name}
                    <div className="widget-setting-title">
                      {messages('setting.key568'/* 标题 */)}
                      :
                      {structureNowWidget.name}
                    </div>
                    <div className="field-tips">
                      <div className="widget-setting-title">
                        提示信息: &nbsp;
                        <Switch
                          checked={oisTipsShow || false}
                          checkedChildren={<Icon type="check" />}
                          unCheckedChildren={<Icon type="cross" />}
                          onChange={(checked) => this.setState({ oisTipsShow: checked })}
                         />
                      </div>
                      {oisTipsShow && (
                        <div>
                          <Input
                            placeholder="请输入提示信息"
                            onChange={(e) => this.setState({ ofieldTips: e.target.value })}
                            value={ofieldTips || ''} />
                        </div>
                      )}
                    </div>
                    <div className="widget-setting-title">
                      <Checkbox
                        onChange={(e) => this.handleChangeStructureCheckBox(e, 'timeSupported')}
                        defaultChecked={expenseType.timeSupported}
                        disabled={!tenantMode}>
                        {messages('setting.key1506')/* 是否启用时分 */}
                      </Checkbox>
                    </div>
                    <div className="form-title">{messages('setting.key1803')/* 默认值 */}</div>
                    <div className="widget-setting-title">
                      <RadioGroup disabled={!tenantMode}
                                  onChange={(e) => this.handleChangeStructureCheckBox(e, 'autoTimeSupported')}
                                  value={occurDateDefaultValue}>
                        <Radio value="CURRENT">{messages('setting.key1828')/* 当天日期（时分） */}</Radio>
                        <Radio value="NOTHING">{messages('setting.key1829')/* 无默认值 */}</Radio>
                      </RadioGroup>
                    </div>
                    <div className="form-title">{messages('setting.key1991')/* 联动值 */}</div>
                    <div className="widget-setting-title">
                      <RadioGroup disabled={!tenantMode}
                                  onChange={(e) => this.handleChangeStructureCheckBox(e, 'dateLinkageValue')}
                                  value={dateLinkageValue}>
                        <Radio value="none">{messages('setting.key1992')/* 不随其他控件值联动 */}</Radio>
                        <br />
                        <Radio value="115_start_date">{messages('setting.key1993')/* 随【开始结束日期控件】开始日期联动 */}</Radio>
                        <br />
                        <Radio value="115_end_date">{messages('setting.key1994')/* 随【开始结束日期控件】结束日期联动 */}</Radio>
                      </RadioGroup>
                    </div>
                  </If>
                  <If value={structureNowWidget.messageKey === 'form.description'}>
                    <div className="form-title">
                      {' '}
                      {messages('setting.key1758')/* 说明文字 */}
                      ：
                      <Switch onChange={this.handleFormDescChange}
                              checked={promptInfo.enabled}
                              disabled={!tenantMode}
                              checkedChildren={<Icon type="check" />}
                              unCheckedChildren={<Icon type="cross" />} />
                      <div className="form-title-description">
                        {' '}
                        {messages('setting.key1759')/* 启用后，所有角色均可在费用详情页查看说明内容（该内容不参与打印） */}
                      </div>
                    </div>
                    <If value={promptInfo.enabled}>
                      <div className="form-title">{messages('components.key611'/* 标题 */)}</div>
                      <LanguageInput nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'promptTitle')}
                                     width="100%"
                                     name={promptInfo.promptTitle}
                                     disabled={!tenantMode}
                                     isEdit
                                     inpRule={[
                                       {length: 100, language: 'zh_cn'},
                                       {length: 300, language: 'en'}
                                     ]}
                                     mainLanguageIsRequired={false}
                                     i18nName={(promptInfo.i18n || {}).promptTitle} />
                      <div className="form-title">{messages('components.key620'/* 描述内容 */)}</div>
                      <LanguageInput nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'promptContent')}
                                     width="100%"
                                     disabled={!tenantMode}
                                     name={promptInfo.promptContent}
                                     isEdit
                                     inpRule={[
                                       {length: 600, language: 'zh_cn'},
                                       {length: 1800, language: 'en'}
                                     ]}
                                     textArea
                                     mainLanguageIsRequired={false}
                                     i18nName={(promptInfo.i18n || {}).promptContent} />
                    </If>
                  </If>
                  <If value={structureNowWidget.fieldType === 'comment'}>
                    {messages('setting.key505'/* 类型 */)}
                    :
                    {structureNowWidget.name}
                    <div className="widget-setting-title">
                      {messages('setting.key568'/* 标题 */)}
                      :
                      {' '}
                      {structureNowWidget.name}
                    </div>
                    <div className="field-tips">
                      <div className="widget-setting-title">
                        提示信息: &nbsp;
                        <Switch
                          checked={pisTipsShow || false}
                          checkedChildren={<Icon type="check" />}
                          unCheckedChildren={<Icon type="cross" />}
                          onChange={(checked) => this.setState({ pisTipsShow: checked })}
                         />
                      </div>
                      {pisTipsShow && (
                        <div>
                          <Input
                            placeholder="请输入提示信息"
                            onChange={(e) => this.setState({ pfieldTips: e.target.value })}
                            value={pfieldTips || ''} />
                        </div>
                      )}
                    </div>
                    <CommentSetting
                      fieldType="comment"
                      expenseType={expenseType}
                      onChange={(originExpenseType, name, i18n) => {
                        this.setState({ originExpenseType });
                        this.handleLanguageInput(name, i18n, 'titlePlaceholder');
                      }}
                    />
                    <div className="widget-setting-title">
                      <Checkbox
                        checked={titleRequired}
                        disabled={!tenantMode}
                        onChange={(e) => this.setState({ titleRequired: e.target.checked })}
                      >
                        {messages('setting.key570'/* 是否必填 */)}
                      </Checkbox>
                    </div>
                  </If>
                  <If value={structureNowWidget.fieldType === 'attachment'}>
                    {messages('setting.key505'/* 类型 */)}
                    :
                    {structureNowWidget.name}
                    <div className="widget-setting-title">
                      {messages('setting.key568'/* 标题 */)}
                      :
                      {' '}
                      {structureNowWidget.name}
                    </div>
                    <div className="field-tips">
                      <div className="widget-setting-title">
                        提示信息: &nbsp;
                        <Switch
                          checked={fisTipsShow || false}
                          checkedChildren={<Icon type="check" />}
                          unCheckedChildren={<Icon type="cross" />}
                          onChange={(checked) => this.setState({ fisTipsShow: checked })}
                         />
                      </div>
                      {fisTipsShow && (
                        <div>
                          <Input
                            placeholder="请输入提示信息"
                            onChange={(e) => this.setState({ ffieldTips: e.target.value })}
                            value={ffieldTips || ''} />
                        </div>
                      )}
                    </div>
                  </If>
                </div>
              ) : messages('setting.key577'/* 请从左侧列表拖入组件 */)
            )}
            {(structureNowWidget || expenseType.fields.length > 0 || nowWidgets.length > 0) && tenantMode && (
              <div className="widget-setting-buttons">
                <Button type="primary" onClick={this.handleSave} loading={saving}>{messages('common.save')}</Button>
                <Popover
                  content={this.renderPreviewQCode()}
                  trigger="click"
                  placement="bottomRight"
                  visible={codeVisible}
                  onVisibleChange={(codeVisible) => !this.hasError && this.setState({ codeVisible })}
                  getPopupContainer={(triggerNode) => triggerNode.parentNode}
                >
                  <Button type="primary" style={{marginLeft: 12}} onClick={this.handlePreview}>{messages('setting.key1995')/* 保存并预览 */}</Button>
                </Popover>
              </div>
            )}
          </Col>
        </Row>
      </div>
    );
  }
}

ExpenseTypeCustom.propTypes = {
  expenseType: React.PropTypes.object,
  onSave: React.PropTypes.func,
  saveIndex: React.PropTypes.func,
  index: React.PropTypes.number,
  expenseTypeId: React.PropTypes.string,
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    languageList: state.login.languageList,
    tenantMode: state.main.tenantMode
  };
}

export default connect(mapStateToProps)(withDragDropContext(ExpenseTypeCustom));
